package controller;

import java.io.*;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import dao.ArchiveDao;
import pojo.ArchivePojo;
import pojo.FilePojo;
import pojo.UserlogPojo;
import service.ArchiveService;
import service.FileService;
import service.UserlogService;
import service.UsersService;
import util.MybatisSessionFactory;

@Controller
public class ArchiveController {
	UsersService serviceUser = new UsersService();
	UserlogService serviceLog = new UserlogService();
	ArchiveService serviceArc = new ArchiveService();
	FileService serviceFile = new FileService();

	@RequestMapping(value = "/add.action", method = RequestMethod.POST)
	@ResponseBody
	public String add(
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			@CookieValue(value = "user", defaultValue = "") String user_id,
			HttpServletResponse response) {
		List<ArchivePojo> list2 = serviceArc.queryDecide(archive_id, identity);

		if (0 != list2.size()) {
			return "ERR1";
		}

		else {
			serviceArc.add(user_id, archive_id, identity, name, gender,
					birthday, date_retire1, date_retire2, sp, fc, title,
					seniority);

			ArchivePojo ar = serviceArc.queryid();
			serviceLog.addlog(user_id, String.valueOf(ar.getId()), "添加");
			return "OK";
		}
	}

	@RequestMapping(value = "/queryall.action", method = RequestMethod.POST)
	@ResponseBody
	public List<ArchivePojo> queryall(
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			@CookieValue(value = "user", defaultValue = "") String user_id

	) {
		List<ArchivePojo> list = serviceArc.queryall(user_id, archive_id,
				identity, name, gender, birthday, date_retire1, date_retire2,
				sp, fc, title, seniority);
		return list;

	}

	@RequestMapping(value = "/queryNumber.action", method = RequestMethod.POST)
	@ResponseBody
	public String queryNumber(
			@RequestParam(value = "archiveId", defaultValue = "") String archive_id,
			@CookieValue(value = "user", defaultValue = "") String user_id) {
		List<ArchivePojo> list = serviceArc.queryNumber(archive_id, user_id);
		serviceLog.addlog(user_id, archive_id, "浏览");
		if (0 == list.size()) {
			return "ERR1";
		}
		if (1 < list.size()) {
			return "ERR2";
		}
		return String.valueOf(list.get(0).getId());
	}

	@RequestMapping(value = "/queryOneById.action", method = RequestMethod.GET)
	@ResponseBody
	public List<ArchivePojo> queryOneById(
			@RequestParam(value = "id", defaultValue = "") String id) {
		List<ArchivePojo> list = serviceArc.queryOneById(id);
		return list;
	}

	@RequestMapping(value = "/update.action", method = RequestMethod.POST)
	@ResponseBody
	public String update(
			@RequestParam(value = "id", defaultValue = "") String id,
			@RequestParam(value = "archive_id", defaultValue = "") String archive_id,
			@RequestParam(value = "identity", defaultValue = "") String identity,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "birthday", defaultValue = "") String birthday,
			@RequestParam(value = "date_retire1", defaultValue = "") String date_retire1,
			@RequestParam(value = "date_retire2", defaultValue = "") String date_retire2,
			@RequestParam(value = "sp", defaultValue = "") String sp,
			@RequestParam(value = "fc", defaultValue = "") String fc,
			@RequestParam(value = "title", defaultValue = "") String title,
			@RequestParam(value = "seniority", defaultValue = "") String seniority,
			@CookieValue(value = "user", defaultValue = "") String user_id
	// 从后台到前台用response 从前台到后台用request
	) {

		serviceArc.update(id, user_id, archive_id, identity, name, gender,
				birthday, date_retire1, date_retire2, sp, fc, title, seniority);
		ArchivePojo ar = serviceArc.queryid();
		serviceLog.addlog(user_id, String.valueOf(ar.getId()), "修改");
		return "OK";
	}

	@RequestMapping(value = "/{id}/upload.action", method = RequestMethod.POST)
	@ResponseBody
	public String upload(@PathVariable String id,
			@RequestParam("file") MultipartFile file, HttpServletRequest req,
			@CookieValue(value = "user", defaultValue = "") String user_id) {
		if (file.isEmpty()) {
			System.out.println("未选择文件");
			return "ERROR_NO_FILE";
		}
		try {
			// 在计算机里面存储或传输 用字节形式
			byte[] bytes = file.getBytes();
			String fileName = file.getOriginalFilename();
			String fileExtension = fileName
					.substring(fileName.lastIndexOf(".") + 1);
			String newFileName = String.valueOf(System.currentTimeMillis())
					+ "." + fileExtension;
			SqlSession session = MybatisSessionFactory.getSqlSession();
			ArchiveDao dao = session.getMapper(ArchiveDao.class);
			List<ArchivePojo> archive = dao.queryOneById(id);
			String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
					.getServletContext().getRealPath("/"), "upload", archive
					.get(0).getArchive_id().toString(), newFileName);
			File existsFile = new File(filePath);
			if (!existsFile.getParentFile().exists()) {
				if (!existsFile.getParentFile().mkdirs()) {
					System.out.println("创建目录失败");
					return "ERROR_ON_MKDIR";
				}
			}
			if (existsFile.exists()) {
				if (existsFile.delete()) {
				} else {
					System.out.println("删除文件失败：" + filePath);
				}
			}
			BufferedOutputStream stream = new BufferedOutputStream(
					new FileOutputStream(new File(filePath)));
			stream.write(bytes);
			stream.close();
			serviceFile.addFile(id, newFileName);
			serviceLog.addlog(user_id, id, "上传图片");
			session.commit();
			return "OK";
		} catch (Exception e) {
			e.printStackTrace();
			return "ERROR";
		}
	}

	@RequestMapping(value = "/queryPhoto.action", method = RequestMethod.GET)
	@ResponseBody
	public List<FilePojo> queryPhoto(
			@RequestParam(value = "id", defaultValue = "") String id

	) {

		List<FilePojo> list = serviceFile.queryPhoto(id);
		return list;

	}

	@RequestMapping(value = "/PhotoDes.action", method = RequestMethod.GET)
	@ResponseBody
	public List<FilePojo> PhotoDes(
			@RequestParam(value = "id", defaultValue = "") String id

	) {
		List<FilePojo> list = serviceFile.PhotoDes(id);
		return list;

	}

	@RequestMapping(value = "/delFile.action", method = RequestMethod.POST)
	@ResponseBody
	public String delFile(
			@RequestParam(value = "id", defaultValue = "") String id,
			HttpServletRequest req) {
		List<FilePojo> file = serviceFile.PhotoDes(id);
		String filePath = String.format("%s\\%s\\%s\\%s", req.getSession()
				.getServletContext().getRealPath("/"), "upload", file.get(0)
				.getArchive_id().toString(), file.get(0).getName().toString());
		File existsFile = new File(filePath);
		existsFile.delete();
		serviceFile.delFile(id);
		return "OK";
	}

	@RequestMapping(value = "/count.action", method = RequestMethod.POST)
	@ResponseBody
	public List<Map> count(
			@RequestParam(value = "starttime", defaultValue = "") String starttime,
			@RequestParam(value = "endtime", defaultValue = "") String endtime
			) {
		List<Map> list = serviceLog.count(starttime, endtime);
		return list;

	}

	@RequestMapping(value = "/queryBrowse.action", method = RequestMethod.GET)
	@ResponseBody
	public List<ArchivePojo> queryBrowse(
			@CookieValue(value = "user", defaultValue = "") String user_id

	) {
		List<ArchivePojo> list = serviceArc.queryBrowse(user_id);
		return list;

	}

	@RequestMapping(value = "/queryRecentlyAdd.action", method = RequestMethod.GET)
	@ResponseBody
	public List<ArchivePojo> queryRecentlyAdd(
			@CookieValue(value = "user", defaultValue = "") String user_id

	) {
		List<ArchivePojo> list = serviceArc.queryRecentlyAdd(user_id);

		return list;

	}
}
